package love.contact.engine;

import java.lang.reflect.Method;

import com.android.internal.telephony.ITelephony;

import love.contact.data.Setting;
import wwk.common.phone.StartReceiver;
import android.content.Context;
import android.content.Intent;
import android.media.AudioManager;
import android.net.Uri;
import android.os.RemoteException;
import android.telephony.TelephonyManager;
import android.util.Log;

//http://www.cnblogs.com/haowenbiao/archive/2012/08/15/2639579.html

public class PhoneBroadcastReceiver extends StartReceiver {

	public void onReceive(Context context, Intent intent) 
	{
		Setting setting=new Setting();
        setting.load(context);
		if(!setting.isMonitorServiceEnabled())
		{
			return;
		}
		
		Log.d("PhoneBroadcastReceiver onReceive",intent.getAction());

		String state = intent.getStringExtra(TelephonyManager.EXTRA_STATE);  
        String number = intent.getStringExtra(TelephonyManager.EXTRA_INCOMING_NUMBER); 
        if(state!=null && state.equals(TelephonyManager.EXTRA_STATE_RINGING))
        {       
        	AudioManager audioManager = (AudioManager)context.getSystemService(Context.AUDIO_SERVICE);
        	
         	if(number!=null && number.equals("18902232704--"))
         	{
         		//Turn ringtone silent
         		audioManager.setRingerMode(AudioManager.RINGER_MODE_SILENT);  
         		
                TelephonyManager telephonyMgr = (TelephonyManager)context.getSystemService(Context.TELEPHONY_SERVICE);  
                try 
                {  
                	Method getITelephonyMethod = TelephonyManager.class.getDeclaredMethod("getITelephony", (Class[]) null);  
                	getITelephonyMethod.setAccessible(true);  
                	ITelephony iTelephony = (ITelephony) getITelephonyMethod.invoke(telephonyMgr, (Object[]) null); 
                	iTelephony.endCall();  
                } 
                catch (Exception e) 
                {  
                	e.printStackTrace();  
             	}  
      
         		audioManager.setRingerMode(AudioManager.RINGER_MODE_NORMAL);  
         	}  
        }  
	
		super.onReceive(context, intent);
		
		if (intent.getAction().equals(Intent.ACTION_BOOT_COMPLETED))
		{
			//when system start finish,start phone monite service.
			//another call sub cods is in Activity,when Activity Started
			PhoneService.startService(context);
		} 
		else if (intent.getAction().equals("love.contact.action.ALARM"))
		{
			//more times call startService will not start more service,it will call onStart more times. 
			context.startService(new Intent(context,PhoneService.class));
		}
	}
}